<?php

namespace App\Admin\Repositories;

use App\Models\ActivityPrize as Model;
use Dcat\Admin\Repositories\EloquentRepository;
use Dcat\Admin\Form;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;

class ActivityPrize extends EloquentRepository
{
    /**
     * Model.
     *
     * @var string
     */
    protected $eloquentClass = Model::class;

    /**
     * 新增记录.
     *
     * @param  Form  $form
     * @return mixed
     */
    public function store(Form $form)
    {
        $result = null;

        DB::transaction(function () use ($form, &$result) {
            $model = $this->model();

            $updates = $form->updates();

            [$relations, $relationKeyMap] = $this->getRelationInputs($model, $updates);

            if ($relations) {
                $updates = Arr::except($updates, array_keys($relationKeyMap));
            }

            $updates = $this->changeUpdates($updates);

            foreach ($updates as $column => $value) {
                $model->setAttribute($column, $value);
            }

            $result = $model->save();

            $this->updateRelation($form, $model, $relations, $relationKeyMap);
        });

        return $this->model()->getKey();
    }

    /**
     * 更新数据.
     *
     * @param  Form  $form
     * @return bool
     */
    public function update(Form $form)
    {
        /* @var EloquentModel $builder */
        $model = $this->model();
        if (!$model->getKey()) {
            $model->exists = true;

            $model->setAttribute($model->getKeyName(), $form->getKey());
        }

        $result = null;

        DB::transaction(function () use ($form, $model, &$result) {
            $updates = $form->updates();

            [$relations, $relationKeyMap] = $this->getRelationInputs($model, $updates);

            if ($relations) {
                $updates = Arr::except($updates, array_keys($relationKeyMap));
            }

            $updates = $this->changeUpdates($updates);

            foreach ($updates as $column => $value) {
                /* @var EloquentModel $model */
                $model->setAttribute($column, $value);
            }

            if (isset($model->valid_at_type)) unset($model->valid_at_type);
            if (isset($model->valid_at_datatime)) unset($model->valid_at_datatime);
            if (isset($model->valid_at_days)) unset($model->valid_at_days);
            if (isset($model->due_at_type)) unset($model->due_at_type);
            if (isset($model->due_at_datatime)) unset($model->due_at_datatime);
            if (isset($model->due_at_days)) unset($model->due_at_days);
            if (isset($model->due_at_months)) unset($model->due_at_months);
            if (isset($model->due_at_years)) unset($model->due_at_years);

            $result = $model->update();

            $this->updateRelation($form, $model, $relations, $relationKeyMap);
        });

        return $result;
    }

    /**
     * 查询编辑页面数据.
     *
     * @param  Form  $form
     * @return array|\Illuminate\Contracts\Support\Arrayable
     */
    public function edit(Form $form)
    {
        $query = $this->newQuery();

        if ($this->isSoftDeletes) {
            $query->withTrashed();
        }

        $this->model = $query
            ->with($this->getRelations())
            ->findOrFail($form->getKey(), $this->getFormColumns());

        if ($this->model->valid_at == 'now' || empty($this->model->valid_at)) {
            $this->model->setAttribute('valid_at_type', 'now');
        } else {
            if (is_datetime($this->model->valid_at)) {
                $this->model->setAttribute('valid_at_type', 'datetime');
                $this->model->setAttribute('valid_at_datatime', $this->model->valid_at);
            } else {
                $arr = explode(' ', $this->model->valid_at);
                $n = ltrim($arr[0], '+');
                $t = $arr[1];
                $this->model->setAttribute('valid_at_type', $t);
                $this->model->setAttribute('valid_at_' . $t, $n);
            }
        }

        if (!empty($this->model->due_at)) {
            if (is_datetime($this->model->due_at)) {
                $this->model->setAttribute('due_at_type', 'datetime');
                $this->model->setAttribute('due_at_datatime', $this->model->due_at);
            } else {
                $arr = explode(' ', $this->model->due_at);
                $n = ltrim($arr[0], '+');
                $t = $arr[1];
                $this->model->setAttribute('due_at_type', $t);
                $this->model->setAttribute('due_at_' . $t, $n);
            }
        }
        return $this->model;
    }

    private function changeUpdates($updates)
    {
        if (isset($updates['valid_at_type'])) {
            switch ($updates['valid_at_type']) {
                case 'datetime':
                    $valid_at = $updates['valid_at_datatime'];
                    break;
                case 'days':
                    $valid_at = '+' . $updates['valid_at_days'] . ' days';
                    break;
                default:
                    $valid_at = 'now';
                    break;
            }

            $updates['valid_at'] = $valid_at;
            unset($updates['valid_at_type']);
            unset($updates['valid_at_datatime']);
            unset($updates['valid_at_days']);

            switch ($updates['due_at_type']) {
                case 'datetime':
                    $due_at = $updates['due_at_datatime'];
                    break;
                case 'days':
                    $due_at = '+' . $updates['due_at_days'] . ' days';
                    break;
                case 'months':
                    $due_at = '+' . $updates['due_at_months'] . ' months';
                    break;
                case 'years':
                    $due_at = '+' . $updates['due_at_years'] . ' years';
                    break;
                default:
                    $due_at = null;
                    break;
            }
            $updates['due_at'] = $due_at;
            unset($updates['due_at_type']);
            unset($updates['due_at_datatime']);
            unset($updates['due_at_days']);
            unset($updates['due_at_months']);
            unset($updates['due_at_years']);
        }
        return $updates;
    }
}
